package com.cdu.supermarket.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesUtils {

    private static final String secretKey = "VpV2UosNCVe9pfzo";
    private static final String fixedIV = "0123456789abcdef"; // 16字节的固定IV，用于测试

    /**
     * 解密
     * @param encryptedText
     * @return
     * @throws Exception
     */
    public static String decryptAESWithFixedIV(String encryptedText) throws Exception {
        // Base64解码整个字符串
        byte[] combined = Base64.getDecoder().decode(encryptedText);

        // 检查长度是否足够包含IV
        if (combined.length < 16) {
            throw new IllegalArgumentException("无效的加密文本：长度不足");
        }

        // 分离IV和加密数据 (前16字节是IV)
        byte[] ivBytes = new byte[16];
        byte[] encryptedBytes = new byte[combined.length - 16];

        System.arraycopy(combined, 0, ivBytes, 0, 16);
        System.arraycopy(combined, 16, encryptedBytes, 0, encryptedBytes.length);

        // 准备密钥
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        // 初始化解密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));

        // 执行解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 加密
     *
     * @param rawPassword
     * @return
     * @throws Exception
     */
    public static String encryptAESWithFixedIV(String rawPassword) throws Exception {
        // 将固定IV字符串转为字节数组
        byte[] ivBytes = fixedIV.getBytes(StandardCharsets.UTF_8);
        // 将密钥字符串转为字节数组
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivBytes));

        byte[] encryptedBytes = cipher.doFinal(rawPassword.getBytes(StandardCharsets.UTF_8));

        // 组合IV和密文: IV(16字节) + 密文
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

        return Base64.getEncoder().encodeToString(combined);
    }
}